﻿using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using DTO;

namespace DAO
{
    public class DuongDAO : DataProvider
    {
        protected override object GetDataRowFromDataReader(OleDbDataReader dr)
        {
            DuongDTO duongDTO = new DuongDTO();            
            if (!dr.IsDBNull(0))
            {
                duongDTO.MaDuong = dr.GetInt32(0);
            }

            if (!dr.IsDBNull(1))
            {
                duongDTO.TenDuong = dr.GetString(1);
            }

            return (object)duongDTO;
        }

        public DuongDTO Search(int id)
        {
            DuongDTO duongDTO = null;
            try
            {
                string strSQL = @"SELECT *" +
                                @" FROM DUONG" +
                                @" WHERE MaDuong = " + id.ToString();

                using (OleDbDataReader dr = this.ExcuteReader(strSQL))
                {
                    if (dr.Read())
                    {
                        duongDTO = (DuongDTO)GetDataRowFromDataReader(dr);
                    }
                }
            }
            catch (Exception ex)
            {
                duongDTO = null;
            }

            return duongDTO;
        }

        public List<DuongDTO> GetAllDuongDTO()
        {
            List<DuongDTO> lstDuongDTO = new List<DuongDTO>();
            try
            {
                string strSQL = @"SELECT *" +
                                @" FROM DUONG";

                using (OleDbDataReader dr = this.ExcuteReader(strSQL))
                {
                    while (dr.Read())
                    {
                        DuongDTO DuongDTO = (DuongDTO)GetDataRowFromDataReader(dr);
                        lstDuongDTO.Add(DuongDTO);
                    }
                }
            }
            catch (Exception ex)
            {
                lstDuongDTO = new List<DuongDTO>();
            }

            return lstDuongDTO;
        }

        public int GetIdByName(string name)
        {
            int maDuong = -1;
            try
            {
                string strSQL = @"SELECT MaDuong" +
                                @" FROM DUONG" +
                                @" WHERE TenDuong = '" + name + "'";

                using (OleDbDataReader dr = this.ExcuteReader(strSQL))
                {
                    if (dr.Read())
                    {
                        maDuong = dr.GetInt32(0);
                    }
                }
            }
            catch (Exception ex)
            {
                maDuong = -1;
            }

            return maDuong;
        }
    }
}
